//
//  IFAddScheduingPersonVC.m
//  Medicare
//
//  Created by admin on 2017/8/10.
//  Copyright © 2017年 medicare. All rights reserved.
//
//
//  IFTemplateManageListVC.m
//  Medicare
//
//  Created by admin on 2017/7/6.
//  Copyright © 2017年 medicare. All rights reserved.
//

#import "IFAddScheduingPersonVC.h"
#import "IFTemplateManagerCell.h"
#import "IFMySchedulingPublicDefines.h"
#import "IFLYStringUtil.h"
#import "IFSchedulDocPersonModel.h"
#import "ZYPinYinSearch.h"


#define NAVBAR_HEIGHT 64 //导航栏高度
#define kSearchHeight 36
#define WS(weakSelf)  __weak __typeof(&*self)weakSelf = self;
@interface IFAddScheduingPersonVC ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate> {
    __block BOOL isEditstate;
}
@property (nonatomic,strong) IFLYSearchBar *search;
@property (nonatomic) UITableView *tableView;
@property (nonatomic)CGFloat height;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)NSMutableArray *indexTitles;
@property (nonatomic)CGPoint nowOfferSet;
@property (nonatomic) MyNavbar *nav;
@property (nonatomic,strong) UIButton * rightBtn;
@property (nonatomic,strong) UIButton * leftBtn;
@property (nonatomic,strong) UIButton * cancelBtn;
@property (nonatomic,strong) NSString * searchTag;
@property (nonatomic,strong) UIView * backGroundView;
@property (nonatomic,strong) NSMutableArray *searchDataSourArray; //搜索需要用的数据源
@end
static NSString *identifier = @"IFTemplateManagerCellID";
@implementation IFAddScheduingPersonVC

- (void)viewDidLoad {
    [super viewDidLoad];
    //self.selectArray = [NSMutableArray arrayWithCapacity:0];
    [self creatSearchView];
    [self loadNav];
    self.view.backgroundColor = [UIColor whiteColor];
   
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.nav.frame) + 36 + 10, kScreenWidth, kScreenHeight - CGRectGetMaxY(self.nav.frame) - 36 - 10)];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"IFTemplateManagerCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:identifier];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    /*
    WS(weakself)
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakself loadData];
    }];
     */
    [SVProgressHUD showWithStatus:@"加载中..."];
    [self loadData];
}

#pragma -mark 请求数据
- (void)loadData {
    [[IFly_APIManager shareManager] api_getDeptUsersContactListWithDeptCode:nil/*DEPT_ID*/ andBackBlock:^(BackDataVO *data, NSError *error) {
        [SVProgressHUD dismiss];
        if (data) {
            if ([data.s isEqualToString:@"1"]) {
                NSArray *userVO = [IFSchedulDepartmentModel mj_objectArrayWithKeyValuesArray:data.r];
                IFSchedulDepartmentModel * departmentModelModel = [userVO firstObject];
                departmentModelModel.dptCode = [UserService share].currentAccount.selectedDeptCode;
                NSMutableArray * array = [NSMutableArray arrayWithCapacity:0];
                for (NSDictionary *dic in departmentModelModel.userContacts) {
                    IFSchedulDocPersonModel *model = [IFSchedulDocPersonModel mj_objectWithKeyValues:dic];
                    for (IFSchedulDocPersonModel * personModel in self.selectArray) {
                        if ([model.username isEqualToString:personModel.username]) {
                            model.classArrangementList = personModel.classArrangementList;
                            model.shouPin = personModel.shouPin;
                        }
                    }
                    model.dptCode = departmentModelModel.dptCode;
                    [array addObject:model];
                }
                [self.tableView.mj_header endRefreshing];
                self.searchDataSourArray = [NSMutableArray arrayWithArray:array];
                [self.dataArray removeAllObjects];
                [self.dataArray addObjectsFromArray:[self sortShouPinWithDataArray:array]];
                [self.tableView reloadData];
            } else {
                  [self.tableView.mj_header endRefreshing];
                if (![data.ec containsString:@"00034"]) {
                    [SVProgressHUD showTextHUD:data.em];
                }
            }
        }
    }];
}

- (void)creatSearchView {
    self.search = [[IFLYSearchBar alloc] initWithFrame:CGRectMake(20, IFLY_kNavTopHeight + 5, kScreenWidth - 40, kSearchHeight)];
    self.search.placeholder = @"搜索";
    self.search.backgroundColor=[UIColor whiteColor];
    UIImage* clearImg = [Common imageWithColor:[UIColor clearColor] andHeight:32.0f];
    [self.search setBackgroundImage:clearImg];
    [self.search setSearchFieldBackgroundImage:clearImg forState:UIControlStateNormal];
    [self.search setBackgroundColor:[UIColor clearColor]];
    self.search.delegate = self;
    [self.view addSubview: self.search];
    self.search.layer.masksToBounds = YES;
    self.search.layer.cornerRadius = 18;
    self.search.layer.borderWidth = 0.5;
    self.search.layer.borderColor = IFLY_MAIN_LINE_COLOR.CGColor;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)loadNav {
    WS(weakSelf)
    self.nav = [[MyNavbar alloc] initWithTitle:@"编辑人员" Image:nil rightTitle:@"完成" andController:self];
    [self.nav show];
    self.rightBtn = [self.nav getRightBtn];
    self.leftBtn = [self.nav getleftBtn];
    self.nav.rightBlock = ^{
        if ([weakSelf.delegate respondsToSelector:@selector(passValueForAddScheduingPersonAndArray:)]&&weakSelf.delegate) {
            [weakSelf.delegate passValueForAddScheduingPersonAndArray:weakSelf.selectArray];
        }
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *secArray = self.dataArray[section];
    return secArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray * sectionArray = self.dataArray[indexPath.section];
    IFSchedulDocPersonModel *temp = sectionArray[indexPath.row];
    __weak IFAddScheduingPersonVC * weakSelf = self;
    IFTemplateManagerCell  *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.stateBtn setImage:[UIImage imageNamed:@"consulationRadioButtonUnselected"] forState:UIControlStateNormal];
    [cell.stateBtn setImage:[UIImage imageNamed:@"consulationRadioButtonSelected"] forState:UIControlStateSelected];
    cell.titleLabel.text = temp.realName;
    cell.rightImageView.hidden = YES;
    if ([self.selectArray containsObject:temp]) {
        cell.stateBtn.selected = YES;
    } else {
        cell.stateBtn.selected = NO;
    }
    cell.leftConDistance.constant = 24 + 24;
    cell.lineLeftConDistance.constant = 12.f;
    cell.stateBtn.hidden = NO;
    cell.selectTemplateManagerBlock = ^(UIButton * sender) {
        if ([weakSelf.selectArray containsObject:temp]) {
            [weakSelf.selectArray removeObject:temp];
            sender.selected = NO;
        } else {
            [weakSelf.selectArray addObject:temp];
            sender.selected = YES;
        }
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray * sectionArray = self.dataArray[indexPath.section];
    IFSchedulDocPersonModel *temp = sectionArray[indexPath.row];
    IFTemplateManagerCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if ([self.selectArray containsObject:temp]) {
        [self.selectArray removeObject:temp];
        cell.stateBtn.selected = NO;
    } else {
        [self.selectArray addObject:temp];
        cell.stateBtn.selected = YES;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.indexTitles;
}

//返回每个索引的内容
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.indexTitles[section];
}

//响应点击索引时的委托方法
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index {
    [SVProgressHUD showTextHUD:title];
    return index;
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    [self.view endEditing:YES];
}

#pragma mark ---  排序
- (NSArray *)sortShouPinWithDataArray:(NSArray *)array {
    NSMutableArray *sortArray = [NSMutableArray array];
    NSMutableDictionary *sortDictory = [NSMutableDictionary dictionary];
    [self.indexTitles removeAllObjects];
    for (IFSchedulDocPersonModel *caseTemp in array) {
        NSMutableArray *tempArr = [sortDictory valueForKey:caseTemp.shouPin];
        if (tempArr) {
            [tempArr addObject:caseTemp];
        } else {
            NSMutableArray *newTempArr = [NSMutableArray array];
            [newTempArr addObject:caseTemp];
            [sortDictory setValue:newTempArr forKey:caseTemp.shouPin];
            [self.indexTitles addObject:caseTemp.shouPin];
        }
    }
    self.indexTitles = [Common sortFirstStrWithArray:self.indexTitles];
    NSString *shoupin = [self.indexTitles firstObject];
    if ([shoupin isEqualToString:@"#"]) {
        [self.indexTitles removeObjectAtIndex:0];
        [self.indexTitles addObject:@"#"];
    }
    for (NSString *shoupin in self.indexTitles) {
        [sortArray addObject:[sortDictory valueForKey:shoupin]];
    }
    return sortArray;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)indexTitles {
    if (!_indexTitles) {
        _indexTitles = [NSMutableArray array];
    }
    return _indexTitles;
}

- (NSMutableArray *)getSepTextArray:(NSString *)content {
    NSString *tempStr = [content stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSString *temp1 = [tempStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    NSMutableArray *tags = [IFLYStringUtil seperateString:[temp1 stringByReplacingOccurrencesOfString:@" " withString:@""]];
    return tags;
}

#pragma mark - UISearchBarDelegate 协议
// 取消按钮被按下时，执行的方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self searchInterface:searchText];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    
}

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    
    return YES;
}

- (void)searchInterface:(NSString *)searchText {
    [ZYPinYinSearch searchByPropertyName:@"realName" withOriginalArray:self.searchDataSourArray searchText:searchText success:^(NSArray *results) {
        if (searchText.length > 0) {
            if (results.count > 0 ) {
                self.backGroundView.hidden = YES;
            } else {
                [self.view addSubview:self.backGroundView];
                self.backGroundView.hidden = NO;
            }
            self.dataArray = [NSMutableArray arrayWithArray:[self sortShouPinWithDataArray:results]];
        } else {
            self.backGroundView.hidden = YES;
            self.dataArray = [NSMutableArray arrayWithArray:[self sortShouPinWithDataArray:self.searchDataSourArray]];
        }
        [self.tableView reloadData];
    } failure:^(NSString *errorMessage) {
        
    }];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    return  YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    if (self.cancelBtn) {
        [self.cancelBtn removeFromSuperview];
    }
    self.cancelBtn = [[UIButton alloc] init];
    self.cancelBtn.frame = CGRectMake(kScreenWidth - 70, 69 + 3, 50, 30);
    [self.cancelBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.cancelBtn setTitle:@"取消" forState:0];
    self.cancelBtn.titleLabel.font = IFLY_SYS_FONT(16);
    [self.cancelBtn addTarget:self action:@selector(canBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.cancelBtn];
    self.cancelBtn.hidden = NO;
    _searchTag = @"1";
    [searchBar setShowsCancelButton:YES];
    for(id cc in [searchBar.subviews[0] subviews]) {
        if([cc isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:@"  "  forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            
        }
    }
}

- (void)canBtnClick:(UIButton *)sender {
    self.backGroundView.hidden = YES;
    self.dataArray = [NSMutableArray arrayWithArray:[self sortShouPinWithDataArray:self.searchDataSourArray]];
    self.search.text = @"";
    [sender removeFromSuperview];
    [self.search resignFirstResponder];
    [self.search setShowsCancelButton:NO];
    [self.tableView reloadData];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSString *text = searchBar.text;
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (text.length == 0) {
        
    } else {
        _searchTag = @"1";
        if ([searchBar.text isEqualToString:@""]) {
            [self.cancelBtn removeFromSuperview];
        }
        [searchBar resignFirstResponder];
    }
}

- (UIView *)backGroundView {
    if (_backGroundView == nil) {
        
        self.backGroundView = [[UIView alloc]initWithFrame:CGRectMake(0, NAVBAR_HEIGHT+kSearchHeight+10, kScreenWidth, kScreenHeight - NAVBAR_HEIGHT- kSearchHeight-10) ];
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake((CGRectGetWidth(self.backGroundView.frame) - 145)/2.f, (CGRectGetHeight(self.backGroundView.frame) - 145)/2.f, 145, 145)];
        imageView.image = [UIImage imageNamed:@"no_data"];
        [self.backGroundView  addSubview:imageView];
        self.backGroundView.backgroundColor = [UIColor colorWithHexString:@"f2f2f2"];
    }
    return _backGroundView;
}


@end
